//
//  KABThemePreviewVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/17.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABThemePreviewVC.h"
#import "KABModel.h"
#import "KABCosPublishCCell.h"
#import "XDAFNetworking.h"
#import "GlobalHeader.h"
#import "ApiManager.h"
#import "MBProgressHUD+XDPrompt.h"
#import "ThemeManager.h"
#import "UIColor+XDHex.h"

typedef NS_ENUM(NSInteger, SkinBtnState) {
    SkinBtnStateNotDownload = 0,    //!< 未下载
    SkinBtnStateDownloading,        //!< 正在下载
    SkinBtnStateCouldUse,           //!< 可以使用
    SkinBtnStateUsed,               //!< 正在使用
};

@interface KABThemePreviewVC ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UILabel *themeTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UIButton *useBtn;
@property (strong, nonatomic) CALayer *progressLayer;
@property (assign, nonatomic) SkinBtnState skinBtnState;
@property (strong, nonatomic) UIBarButtonItem *delBarBtnItem;

@property (strong, nonatomic) KABSkinDetail *skinDetail;

@end

static NSString *const kReuseCellId = @"KABCosPublishCCell";

@implementation KABThemePreviewVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = self.skinClassItem.name;
}

- (void)initSubViews {
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UINib *cellNib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:kReuseCellId];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    self.useBtn.layer.masksToBounds = YES;
    self.useBtn.layer.cornerRadius = CGRectGetHeight(self.useBtn.bounds) / 2.0;
    [self.useBtn addTarget:self action:@selector(useBtnTapped:) forControlEvents:UIControlEventTouchUpInside];

    self.progressLayer.frame = CGRectMake(0, 0, 0, CGRectGetHeight(self.useBtn.bounds));
    [self.useBtn.layer addSublayer:self.progressLayer];
    
    [self requestSkinDetail];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.skinDetail.introduce_image_list.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    KABCosPublishCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.item < self.skinDetail.introduce_image_list.count) {
        [cell configViewWithSkinDetImgItem:self.skinDetail.introduce_image_list[indexPath.item]];
    }
    return cell;
}

//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
//    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
//        KABThemeMallCRView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kReuseCRViewId forIndexPath:indexPath];
//        return header;
//    } else if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
//        KABThemeMallFooterCRView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:kReuseFooterId forIndexPath:indexPath];
//        return footer;
//    }
//    return nil;
//}

#pragma mark - <UICollectionViewDelegateFlowLayout>
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
//    return CGSizeMake(CGRectGetWidth(self.view.bounds), 45.0);
//}
//
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
//    return CGSizeMake(CGRectGetWidth(self.view.bounds), 6.0);
//}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width = (CGRectGetWidth(self.view.bounds) - 15 - 35) * 4.0 / 5.0;
    CGFloat height = CGRectGetHeight(collectionView.bounds) - 12 * 2;
    return CGSizeMake(width, height);
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ;
}

#pragma mark - delegate
#pragma mark - event response
- (void)delBarBtnItemTapped:(UIBarButtonItem *)item {
    [[ThemeManager sharedManager] deleteThemeWithThemeId:self.skinDetail.skin_id];
    [self refreshWholeView];
}

- (void)useBtnTapped:(UIButton *)btn {
    if (!self.skinDetail.source_url.length) {
        return;
    }
    
    if (self.skinBtnState == SkinBtnStateUsed || self.skinBtnState == SkinBtnStateDownloading) {
        return;
    }
    
    if (self.skinBtnState == SkinBtnStateCouldUse) {
        [[ThemeManager sharedManager] changeThemeWithThemeId:self.skinDetail.skin_id];
        [self refreshWholeView];
        return;
    }
    
    // 检查是否够买过
    if (self.skinDetail.is_bought) {
        [self startDownloadSkin];
        return;
    }
    // 是否是免费的
    if (self.skinDetail.original_price == 0) {
        [self requestSkinFreePay];
    } else {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"暂时只支持免费皮肤"];
    }
}

#pragma mark - private methods
- (void)updateDownloadProgress:(CGFloat)percent {
    CGRect frame = self.progressLayer.frame;
    frame.size.width = CGRectGetWidth(self.useBtn.bounds) * percent;
    self.progressLayer.frame = frame;
}

- (void)startDownloadSkin {
    // 下载
    self.skinBtnState = SkinBtnStateDownloading;
    [[ThemeManager sharedManager] downloadThemePackageWithThemeId:self.skinDetail.skin_id zipUrl:self.skinDetail.source_url progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"下载进度%zd, 总共%zd", downloadProgress.completedUnitCount, downloadProgress.totalUnitCount);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self updateDownloadProgress:((CGFloat)downloadProgress.completedUnitCount/(CGFloat)downloadProgress.totalUnitCount)];
        });
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if (error) {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"下载皮肤包出错"];
        }
        [self refreshWholeView];
    }];
}

- (void)refreshWholeView {
    self.themeTitleLabel.text = self.skinDetail.name;
    NSString * priceStr = @"免费";
    if (self.skinDetail.original_price) {
        priceStr = [NSString stringWithFormat:@"￥%.2f", self.skinDetail.original_price / 100.0];
    }
    self.priceLabel.text = priceStr;
    
    [self.collectionView reloadData];
    
    ThemeState themeState = [[ThemeManager sharedManager] themeStateWithThemeId:self.skinDetail.skin_id];
    switch (themeState) {
        case ThemeStateNotDownload:
            self.skinBtnState = SkinBtnStateNotDownload;
            break;
        case ThemeStateIsUsed:
            self.skinBtnState = SkinBtnStateUsed;
            break;
        default:
            self.skinBtnState = SkinBtnStateCouldUse;
            break;
    }
    
    self.navigationItem.rightBarButtonItem = (themeState == ThemeStateHasDownload) ? self.delBarBtnItem : nil;
}

#pragma mark - network request
- (void)requestSkinDetail {
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@(self.skinClassItem.skin_id) forKey:@"skinpackage_id"];
    if ([KABModel sharedInstance].isLogin) {
        [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"user_id"];
        [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    }
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiSkinpackage] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求皮肤详情返回：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            self.skinDetail = [KABSkinDetail yy_modelWithDictionary:responseObject[KABGlobalJsonKeyResult]];
            [self refreshWholeView];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"获取皮肤详情失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestSkinFreePay {
    // 必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    // 购买门票请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"skinpackage_id" : @(self.skinDetail.skin_id)};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiSkinFreeBuy] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"购买皮肤返回：%@", responseObject);
        [hud hideAnimated:NO];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
//            MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"购买成功"];
//            temp.completionBlock = ^{
//                [self startDownloadSkin];
//            };
            [self startDownloadSkin];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        NSLog(@"购买皮肤失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters
- (CALayer *)progressLayer {
    if (!_progressLayer) {
        _progressLayer = [[CALayer alloc] init];
        _progressLayer.backgroundColor = [UIColor xd_colorWithHex:KABGlobalColorTabBarItemColor].CGColor;
    }
    return _progressLayer;
}

- (UIBarButtonItem *)delBarBtnItem {
    if (!_delBarBtnItem) {
        _delBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"删除" style:UIBarButtonItemStylePlain target:self action:@selector(delBarBtnItemTapped:)];
    }
    return _delBarBtnItem;
}

- (void)setSkinBtnState:(SkinBtnState)skinBtnState {
    _skinBtnState = skinBtnState;
    
    NSUInteger color[4] = {KABGlobalColorTabBarItemColor, KABGlobalColorLoginFontColor, KABGlobalColorTabBarItemColor, KABGlobalColorLoginFontColor};
    [self.useBtn setBackgroundColor:[UIColor xd_colorWithHex:color[self.skinBtnState]]];
    NSArray *titleArray = @[@"立即下载", @"下载中", @"使用", @"使用中"];
    [self.useBtn setTitle:titleArray[self.skinBtnState] forState:UIControlStateNormal];
    if (skinBtnState != SkinBtnStateDownloading) {
        [self updateDownloadProgress:0];
    }
}

@end
